const router = require("koa-router")({
  prefix: "/api/cart"
});
const cartModel = require("../../db/models")["cart"];
const goodsModel = require("../../db/models")["goods"];
const { Op } = require("sequelize");
// 获取个人购物车
router.get("/", async ctx => {
  const id = ctx.$$user.id;
  const cart = await cartModel.findAll({ where: { uid: id } });
  const where = cart.map(c => {
    return {
      id: c.bid
    };
  });
  const goods = await goodsModel.findAll({
    where: {
      [Op.or]: where
    }
  });
  const gs = goods.map(g => {
    const new_g = {
      id: g.id,
      title: g.title,
      price: g.price,
      desc: g.desc
    };
    cart.forEach(c => {
      if (g.id === c.bid) {
        new_g.count = c.count;
      }
    });
    return new_g;
  });
  ctx.body = {
    code: 200,
    data: gs
  };
});

// 新增
router.post("/", async ctx => {
  const id = ctx.$$user.id;
  const { bid, count } = ctx.request.body;
  const cart = await cartModel.create({
    uid: id,
    bid,
    count
  });
  ctx.body = {
    code: 200,
    data: cart
  };
});

// 修改
router.post("/:id", async ctx => {
  const id = ctx.$$user.id;
  const bid = ctx.params.id;
  const { count } = ctx.request.body;
  const cart = await cartModel.update(
    {
      count
    },
    {
      where: {
        bid,
        uid: id
      }
    }
  );
  ctx.body = {
    code: 200,
    data: cart
  };
});

router.delete("/", async ctx => {
  const id = ctx.$$user.id;
  const { bid } = ctx.request.body;
  const cart = await cartModel.destroy({
    where: {
      uid: id,
      bid
    }
  });
  ctx.body = {
    code: 200,
    data: cart
  };
});

module.exports = router;
